const sqlite3 = require('sqlite3').verbose()
const config = require('../config/config.json')

let db = new sqlite3.Database('sndpjs.d')

let existedTables = [];
let configTables = [];
let diff = [];

// 取出配置中的字段名
configTables = config.database.map(v => v.split(' ')[0])

db.serialize(function () {
    db.all("PRAGMA table_info(d);", function (err, tables) {
        existedTables = tables.map(v => v.name)
        diffInc = tableDiff(configTables, existedTables)
        // 添加字段
        diffInc.forEach(v => {
            console.log(`${v.name} will be added into database`)
            db.run(`ALTER TABLE d ADD COLUMN ${config.database[v.index]}`)
        })
        if (!diffInc.length) 
            console.log('database is up-to-date! no further action will be taken')
    });
})

// 比较不同，多的在前少的在后
function tableDiff(a, b) {
    let diff = [];
    a.forEach((v, i) => {
        if (!b.includes(v)) diff.push({
            index: i,
            name: v
        })
    })
    return diff
}